<template>
	<view class="container">
		<view class="btn on" :class="{ active: static === 'on' }" @click="on">开</view>
		<view class="btn off" :class="{ active: static === 'off' }" @click="off">关</view>
	</view>
</template>

<script>
	import {
		ajax
	} from "../../utils/request";
	export default {
		data() {
			return {
				device: {},
				title: '正在连接蓝牙',
				UUID: '',
				serviceu: "", // 服务地址
				txdu: "", // 发送数据
				rxdu: "", // 接收数据
				signal: "", //蓝牙命令
				serviceId: "", //服务id
				characteristicId: "", //特征值id
				hex: "", //蓝牙返回的数据
				code: "", //设备code
				userId: "", //用户id
				ss_mc: "", //宿舍号
				islogin: false, //是否登录
				static: null, //开关状态
				connected: false, //连接状态
			}
		},
		onLoad() {
			console.log("选择的设备", uni.getStorageSync("device"))
			this.device = uni.getStorageSync("device");
			console.log("code:", this.device.code)
			this.code = this.device.code;

			this.userId = uni.getStorageSync('userId');
			this.ss_mc = uni.getStorageSync('userInfo').ss_mc;
			console.log("登录信息:", this.userId || null, this.ss_mc || null)
			if (this.userId && this.ss_mc) {
				this.isLogin = true;
				console.log("已登录");
			} else {
				this.title = "请先登录";
				console.log("请先登录");
			}

			// 判断是否为 iOS
			if (uni.getSystemInfoSync().platform === 'ios') {
				console.log("ios用户");
				this.title = "正在搜索设备ID";
				// 获取设备ID
				this.getBluetoothDeviceIdByName(this.device.BluetoothName)
					.then(deviceId => {
						console.log('找到设备ID:', deviceId);
						this.UUID = deviceId;
						console.log('uuid', this.UUID)
						// 开始连接蓝牙
						this.connect();
					})
					.catch(error => {
						console.error('错误:', error.message);
					});
				// this.UUID = this.device.IOSUUID;
			} else {
				this.UUID = this.device.UUID;
				// 开始连接蓝牙
				this.connect();
			}
			console.log('UUID:', this.UUID)
			// 开始连接蓝牙
			// this.connect();
			uni.showLoading({
				title: this.title,
				mask: true
			});
		},
		methods: {
			on() {
				if (!this.connected) {
					uni.showToast({
						title: '请先连接蓝牙设备',
						icon: 'none'
					});
					return;
				}
				console.log("on");
				this.static = "on"
				this.getSignal("/api/meter/BluetoothOn");
				//返回给后端
			},
			off() {
				if (!this.connected) {
					uni.showToast({
						title: '请先连接蓝牙设备',
						icon: 'none'
					});
					return;
				}
				console.log("off");
				this.static = "off"
				this.getSignal("/api/meter/BluetoothOff");
			},
			//获取命令
			getCommand(api) {
				ajax(api, "POST", {
						userId: this.userId,
						ss_mc: this.ss_mc,
					})
					.then((res) => {
						this.signal = res.data.hexAll;
						this.sendSignal();
					})
					.catch((err) => {
						console.log(err);
					});
			},
			//连接
			connect() {
				this.serviceu = getApp().globalData.mserviceuuid.toUpperCase();
				this.txdu = getApp().globalData.mtxduuid.toUpperCase();
				this.rxdu = getApp().globalData.mrxduuid.toUpperCase();
				let deviceId = this.UUID;
				console.log("开始连接蓝牙", deviceId, this.serviceu, this.txdu, this.rxdu);
				uni.getConnectedBluetoothDevices({
					services: [this.serviceu],
					success: (res) => {
						let isConnected = res.devices.some(device => device.deviceId === deviceId);
						if (isConnected) {
							console.log("设备已连接");
							this.connected = true; // Update the connected status
							this.title = "设备已连接";
							uni.hideLoading();
							this.getBLEDeviceServices(deviceId);
						} else {
							this.createBLEConnection(deviceId);
						}
					},
					fail: (err) => {
						console.error("获取已连接设备失败", err);
						this.createBLEConnection(deviceId);
					}
				});
			},
			//连接蓝牙
			createBLEConnection(deviceId) {
				uni.createBLEConnection({
					deviceId,
					success: (res) => {
						console.log("连接成功", res);
						this.connected = true; // Update the connected status
						this.title = "正在获取服务...";
						this.getBLEDeviceServices(deviceId);
					},
					fail: (err) => {
						console.error("连接失败", err);
						uni.showToast({
							title: '连接失败',
							icon: 'none'
						});
					}
				});
			},
			//获取服务
			getBLEDeviceServices(deviceId) {
				uni.getBLEDeviceServices({
					deviceId,
					success: (res) => {
						console.log("获取服务成功", res);
						let isService = res.services.some(
							(service) => this.serviceu === service.uuid
						);
						if (isService) {
							this.getBLEDeviceCharacteristics(
								deviceId,
								res.services.find((service) => this.serviceu === service.uuid).uuid
							);
							this.title = "获取特征值...";
						} else {
							this.title = "UUID错误";
							uni.showToast({
								title: 'UUID错误',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error("获取服务失败", err);
						uni.showToast({
							title: '获取服务失败',
							icon: 'none'
						});
					}
				});
			},
			//获取特征值
			getBLEDeviceCharacteristics(deviceId, serviceId) {
				uni.getBLEDeviceCharacteristics({
					deviceId,
					serviceId,
					success: (res) => {
						res.characteristics.forEach((item) => {
							if (item.properties.read) {
								uni.readBLECharacteristicValue({
									deviceId,
									serviceId,
									characteristicId: item.uuid,
								});
							}
							if (item.properties.write && this.txdu === item.uuid) {
								this.characteristicId = item.uuid;
								this.serviceId = serviceId;
							}
							if ((item.properties.notify || item.properties.indicate) && this.rxdu ===
								item.uuid) {
								uni.notifyBLECharacteristicValueChange({
									deviceId,
									serviceId,
									characteristicId: item.uuid,
									state: true,
									success: () => {
										this.title = "连接成功";
										uni.hideLoading();
										uni.showToast({
											title: '连接成功',
											icon: 'success'
										});
										this.listen();
									},
									fail: (err) => {
										console.error("启用通知失败", err);
										uni.showToast({
											title: '启用通知失败',
											icon: 'none'
										});
									}
								});
							}
						});
					},
					fail: (err) => {
						console.error("获取特征值失败", err);
						uni.showToast({
							title: '获取特征值失败',
							icon: 'none'
						});
					}
				});
			},
			//获取信号
			getSignal(api) {
				let userInfo = uni.getStorageSync("userInfo");
				ajax(api, "POST", {
						userId: this.userId,
						ss_mc: this.ss_mc,
						code: this.code,
						xh: userInfo.account,
						Name: userInfo.name
					})
					.then((res) => {
						this.signal = res.data.hexAll;
						this.sendSignal(this.signal, 5); // 发送五次信号
						console.log("获取命令成功", this.signal);
					})
					.catch((err) => {
						console.log(err);
					});
			},
			//发送信号
			sendSignal(data, count) {
				console.log("发送信号",data);
				// 字符串转16进制
				let uint8Array = new Uint8Array(data.length / 2);
				for (let i = 0; i < data.length; i += 2) {
					uint8Array[i / 2] = parseInt(data.substr(i, 2), 16);
				}
				let buffer = uint8Array.buffer;
				let stopSending = false; // 标志位，用于中断发送

				// 轮询发送
				const sendData = (sendCount) => {
					if (sendCount < count && !stopSending) {
						setTimeout(() => {
							uni.writeBLECharacteristicValue({
								deviceId: this.UUID,
								serviceId: this.serviceId,
								characteristicId: this.characteristicId,
								value: buffer,
								success: (res) => {
									if (this.static == "on") {
										uni.showToast({
											title: "设备已启动",
											icon: "none"
										});
									}
									stopSending = true; // 发送成功，设置标志位，中断后续发送
								},
								fail: (error) => {
									console.error("蓝牙信号发送失败", error);
									uni.showToast({
										title: "蓝牙信号发送失败",
										icon: "none"
									});
									// 根据需要添加错误处理逻辑
								},
								complete: () => {
									sendData(sendCount + 1); // 递归调用，发送下一次信号
								},
							});
						}, sendCount * 500); // 根据发送次数计算延迟时间
					}
				};

				sendData(0); // 初始化发送计数器
			},
			// 监听数据
			listen() {
				uni.onBLECharacteristicValueChange((characteristic) => {
					console.log('特征值变化:', characteristic);
					const value = characteristic.value;
					let hex = Array.prototype.map.call(new Uint8Array(value), x => ('00' + x.toString(16)).slice(-
						2)).join('');
					console.log('接收到的数据:', hex);
					this.hex = hex;
					if (this.static == "off") {
						// if (hex == "ff") {
						//返回给后端
						this.sendData("/api/meter/BluetoothgetgetOff")

					} else {
						//返回给后端
						this.sendData("/api/meter/BluetoothgetOn")

					}
				});
			},
			//数据回传后端
			sendData(api) {
				let userInfo = uni.getStorageSync('userInfo');
				ajax(api, "POST", {
						userId: this.userId,
						ss_mc: this.ss_mc,
						msg: this.hex,
						code: this.code,
						xh: userInfo.account,
						Name: userInfo.name
					})
					.then((res) => {

						console.log("回传成功", res);
						if (res.data.spendMoney) {
							//断开蓝牙
							uni.closeBLEConnection({
								deviceId: this.UUID,
								success: (res) => {
									console.log('断开蓝牙连接成功', res);
								},
								fail: (err) => {
									console.error('断开蓝牙连接失败', err);
								},
							});
							uni.showModal({
								title: '水表已结束',
								content: `花费金额：${res.data.spendMoney}元`,
								showCancel: false,
								success: function(res) {
									if (res.confirm) {
										// 执行确认后的操作


										//返回上一个页面
										uni.navigateBack({
											delta: 1
										});

									} else {
										// 执行取消后的操作
									}
								}
							})
						}
					})
					.catch((err) => {
						console.log(err);
					});
			},
			//通过蓝牙名获取设备UUID
			getBluetoothDeviceIdByName(deviceName) {
				return new Promise((resolve, reject) => {
					// 开始蓝牙设备扫描
					uni.startBluetoothDevicesDiscovery({
						success: () => {
							// 获取蓝牙设备列表
							const getDevices = () => {
								uni.getBluetoothDevices({
									success: function(res) {
										// 遍历设备列表，寻找名称匹配的设备
										for (let i = 0; i < res.devices.length; i++) {
											if (res.devices[i].name === deviceName) {
												// 找到设备，停止扫描并返回设备ID
												uni.stopBluetoothDevicesDiscovery();
												resolve(res.devices[i].deviceId);
												return;
											}
										}
										// 如果未找到设备，继续扫描
										setTimeout(getDevices, 1000);
									},
									fail: function(err) {
										// 获取设备列表失败，返回错误信息
										uni.stopBluetoothDevicesDiscovery();
										reject(new Error('获取蓝牙设备列表失败：' + err.errMsg));
									}
								});
							};
							// 开始第一次获取设备
							getDevices();
						},
						fail: function(err) {
							// 启动设备扫描失败
							reject(new Error('启动蓝牙设备扫描失败：' + err.errMsg));
						}
					});
				});
			}

		},
	}
</script>

<style scoped lang="scss">
	.container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.btn {
			height: 30vh;
			width: 30vh;
			border-radius: 50%;
			color: #fff;
			text-align: center;
			line-height: 30vh;
			font-size: 80rpx;
			box-shadow: 2px 2px 10px #000;
			margin: 50rpx;
			background-color: #fff;
			color: #000;
			transition: background-color 0.3s, color 0.3s;
		}

		.btn.active {
			background-color: #2ba245;
			color: #fff;
		}

		// .on {
		// 	background-color: #2ba245;
		// }

		// .off {
		// 	background-color: grey;
		// }
	}
</style>